<?php

namespace App\Service\AppStore;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\CallBase;
use App\Model\UserProfile;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use App\Service\BaseService;

/**
 * 匹配请求
 */
class MatchPickService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        //匹配类型
        $matchType = $this->request->input('match_type', 1);
        $where = [
            // ['online', 1],
            ['role', UserProfile::ROLE_HOST],
            ['user_id', '<>', $userId],
        ];
        // if (in_array($matchType, [1, 3])) $where[] = ['online', 1];
        $validUserIds = [1549, 2734, 1661, 1642, 1621, 1653, 1660, 1645, 1663];
        if (!check_dev_env()) {
            $profile = UserProfile::where($where)->whereIn('user_id', $validUserIds)->inRandomOrder()->first();
        } else {
            $where[] = ['online', 1];
            $profile = UserProfile::where($where)->inRandomOrder()->first();
        }

        if (!$profile) {
            return $this->setError(ErrorCode::NO_VALID_HOST, '暂未发现适合你的人，请稍后再试~');
        }
        $userInfo = UserProfile::buildHostItem($profile);
        $userInfo['coin_setting'] = 0; //ConfigUtil::getQuickCallCoin('voice');
        $userInfo['video_coin_setting'] = 0; //ConfigUtil::getQuickCallCoin('video');
        log_info(__CLASS__ . "=={$userId}==" . json_encode($userInfo));

        //创建话单
        switch ($matchType) {
                //语音
            case 1:
                VoiceCall::finishOldCall($userId);
                VoiceCall::addRecord($userId, $userInfo['user_id'], CallBase::FROM_IOS_QUICK_MATCH, $userInfo['coin_setting']);
                break;
                //视频
            case 3:
                VideoCall::finishOldCall($userId);
                VideoCall::addRecord($userId, $userInfo['user_id'], CallBase::FROM_IOS_QUICK_MATCH, $userInfo['video_coin_setting']);
                break;
        }
        return [
            'match_type' => intval($matchType),
            'user_info' => $userInfo,
        ];
    }
}
